package com.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 实现A+1,B-1,C+1,D-1顺序执行
 * */
public class D {
    public static void main(String[] args) {
        Data4 data4 = new Data4();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                data4.increment();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                data4.decrement();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                data4.increment();
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                data4.decrement();
            }
        }, "D").start();
    }
}

class Data4 {
    private Lock lock = new ReentrantLock(); // 可重入锁
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private int num = 0;

    public void increment() {
        lock.lock();
        try {
            // 业务代码
            // 防止虚假唤醒
            while (num != 0) {
                condition1.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName() + "=>" + num);
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            // 业务代码
            // while：防止虚假唤醒
            while (num != 1) {
                condition2.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName() + "=>" + num);
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
